package org.example.com.zwh.controller;

import org.example.com.zwh.dto.SeckillRequest;
import org.example.com.zwh.service.RedisService;
import org.example.com.zwh.service.SeckillService;
import org.example.com.zwh.util.RateLimiterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
public class SeckillController {
    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @PostMapping("/seckill/{productId}")
    public ResponseEntity<String> seckill(
            @PathVariable String productId,
            @RequestParam String userId) {

        RateLimiterUtil rateLimiterUtil = new RateLimiterUtil(redisTemplate);
        //限流检查：每秒最多允许10个请求
        if (!rateLimiterUtil.tryAcquire("rate_limit:" + userId, 10, 1)) {
            return ResponseEntity.status(429).body("请求过于频繁，请稍后再试");
        }

        // 1. 基础校验（用户状态、活动时间等）
        if (!seckillService.validateUser(userId)) {
            return ResponseEntity.badRequest().body("非法用户请求");
        }

        // 2. Redis预减库存（原子操作）
        long stock = seckillService.decrementStock(userId, productId);
        if (stock < 0) {
            System.out.println("商品已售罄-----------------------------");

            return ResponseEntity.ok("商品已售罄");
        }

        // 3. 请求入队（原有逻辑）
        redisService.publishTask(userId, productId);
        return ResponseEntity.ok("排队中，请稍后查询结果");
    }
    @GetMapping("/seckill1")
    public ResponseEntity<String> deleteSeckilL(@PathVariable String productId,
                                                @PathVariable String userId
    ) {
        //删除数据库数据
        seckillService.deleteTask(userId, productId);
        //删除redis数据
        redisService.deleteTask(userId, productId);
        return ResponseEntity.ok("删除成功");
    }
    @GetMapping("/debug/queue")
    public ResponseEntity<?> debugQueue() {
//        List<Object> queueData = redisTemplate.opsForList().range("seckill:queue", 0, -1);

        // 添加调试日志
//        System.out.println("当前队列长度: " + queueData.size());
//        queueData.forEach(item ->
//                System.out.println("条目类型: " + item.getClass().getName() + " 内容: " + item)
//        );
        try {
            redisTemplate.opsForValue().set("test-key", "test-value");
            String value = (String) redisTemplate.opsForValue().get("test-key");
            Long l = redisTemplate.opsForList().rightPush("seckill:queue", "123");
            System.out.println("Redis连接正常，返回值: " + value);
            System.out.println("12312312312，返回值: " + l);

        } catch (Exception e) {
            System.out.println("Redis连接异常: " + e.getMessage());
        }
        //取出redis
        List<Object> queueData = redisTemplate.opsForList().range("seckill:queue", 0, -1);
        return ResponseEntity.ok(queueData);
    }
    @GetMapping("/stats")
    public Map<String, Object> getRealTimeStats() {
        return Map.of(
                "total_requests", redisTemplate.opsForValue().get("seckill:total_requests"),
                "success_orders", redisTemplate.opsForValue().get("seckill:success_orders"),
                "active_users", redisTemplate.opsForHyperLogLog().size("seckill:active_users")
        );
    }
}

